<template>
  <generator-layout>
    <a-config-provider
      :theme="{
        algorithm: isDark ? darkAlgorithm : defaultAlgorithm
      }"
    >
      <router-view v-slot="{ Component: Comp, route }">
        <KeepAlive>
          <component :is="renderNext(route, Comp)" :key="route.meta.key" />
        </KeepAlive>
      </router-view>
    </a-config-provider>
  </generator-layout>
</template>

<script setup lang="ts">
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import type { Component } from 'vue'
import { useGlobalStore, useConfigStore } from '@/store'
import { NAME_STARTUP } from '@/router/constants'
import useMainInvoke from '@/hooks/useMainInvoke'
import { theme } from 'ant-design-vue'

// 上一个解析的组件对象
let lastComponent: Component | null
// router-view + component 有个奇怪的点
// 在路由跳转时会渲染其他一级路由的子页面
// 这里需要判断下一个路由的根路径是否与当前的根路径相同，如果是，返回当前解析的组件对象，否则返回上一个缓存的组件对象
const renderNext = (route: RouteLocationNormalizedLoaded, component: Component): Component | null => {
  const [rootRoute] = route.matched

  if (rootRoute.name !== 'startup') return lastComponent

  lastComponent = component

  return component
}
// 页面离开，释放内存
onDeactivated(() => (lastComponent = null))

const router = useRouter()
const { treeToTranslate, projectId, workspace } = useGlobalStore()
nextTick(() => {
  const { key, label, directory } = treeToTranslate[0]
  router.push({ path: `/${NAME_STARTUP}/${key}`, query: { key, label, directory } })
})

// 切换主题
const { isDark } = toRefs(useConfigStore())
const { darkAlgorithm, defaultAlgorithm } = theme

// 记录项目的 id 与根目录
useMainInvoke('file', 'store-info', { id: projectId, root: workspace })

// 存储当前已存在的字典项
const { setDicts } = useConfigStore()
setDicts()
</script>

<style scoped></style>
